package es.udc.emarketapp.http.controller.actions.categories;

import es.udc.emarketapp.emarket.model.category.vo.CategoryVO;
import es.udc.emarketapp.emarket.model.categoryFacade.CategoryFacade;
import java.util.List;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import es.udc.emarketapp.http.view.actionForms.CategoryForm;
import es.udc.fbellas.j2ee.util.exceptions.InstanceNotFoundException;
import es.udc.fbellas.j2ee.util.exceptions.InternalErrorException;
import es.udc.fbellas.j2ee.util.struts.action.DefaultAction;
import javax.servlet.http.HttpSession;

public class EditCategoryAction extends DefaultAction {

    public ActionForward doExecute(ActionMapping mapping,
            ActionForm form, HttpServletRequest request,
            HttpServletResponse response)
            throws IOException, ServletException, InternalErrorException, InternalErrorException {

        ActionMessages errors = new ActionMessages();

        CategoryForm categoryForm = (CategoryForm) form;

        Long idCat = (Long) categoryForm.getIdCat();
        String nomCat = categoryForm.getNomCat();

        System.out.println("categoria a editar: " + nomCat);
         System.out.println("categoria a editar idCat: " + idCat);

        try {

            CategoryFacade categoryFacade = new CategoryFacade();
            CategoryVO category = categoryFacade.findCategoryById(idCat);
            Long idCatFather = category.getCatPadre();
            categoryForm.setCatFather(idCatFather);
            categoryForm.setNomCat(category.getNomCat());

            CategoryVO categoryFather = categoryFacade.findCategoryById(idCatFather);
            request.setAttribute("nomCatFather", categoryFather.getNomCat());

            try {
                /*path de categoria actual seleccionada*/
                HttpSession session = request.getSession(true);
                List<CategoryVO> listCats = categoryFacade.getCategoryRoute(idCat);
                session.setAttribute("currentCategories", listCats);

            } catch (InstanceNotFoundException e) {
                errors.add("identifier",
                        new ActionMessage("ErrorMessages.category.notFound"));
                saveErrors(request, errors);
            }


        } catch (InstanceNotFoundException e) {
            errors.add("CategoryIdentifier",
                    new ActionMessage("ErrorMessages.category.notFound"));
            saveErrors(request, errors);

            return new ActionForward(mapping.getInput());
        }

        return mapping.findForward("UpdateCategoryForm");
    }
}
